package com.hkfn.rfb.common.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.webkit.WebView;

/**
 * Created by Quanmama on 2018/3/15.
 */

public class GetTopWebView extends WebView {
    private boolean isTop = false;
    private boolean isNeedRefresh = true;
    private SuperSwipeRefreshLayout swipeRefreshLayout;

    public boolean isNeedRefresh() {
        return isNeedRefresh;
    }

    public void setNeedRefresh(boolean needRefresh) {
        isNeedRefresh = needRefresh;
    }

    public SuperSwipeRefreshLayout getSwipeRefreshLayout() {
        return swipeRefreshLayout;
    }

    public void setSwipeRefreshLayout(SuperSwipeRefreshLayout swipeRefreshLayout) {
        this.swipeRefreshLayout = swipeRefreshLayout;
    }

    public GetTopWebView(Context context) {
        super(context);
    }

    public GetTopWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public GetTopWebView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected boolean overScrollBy(int deltaX, int deltaY, int scrollX, int scrollY, int scrollRangeX, int scrollRangeY, int maxOverScrollX, int maxOverScrollY, boolean isTouchEvent) {
        if(scrollY <= 0){
            if(!isTop && deltaY < 0){
                isTop = true;
                if (null != swipeRefreshLayout && isNeedRefresh) {
                    swipeRefreshLayout.setEnabled(true);
                }
            }
        }
        return super.overScrollBy(deltaX, deltaY, scrollX, scrollY, scrollRangeX, scrollRangeY, maxOverScrollX, maxOverScrollY, isTouchEvent);
    }

    @Override
    protected void onOverScrolled(int scrollX, int scrollY, boolean clampedX, boolean clampedY) {
        super.onOverScrolled(scrollX, scrollY, clampedX, clampedY);
    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);
    }

    public boolean isTop() {
        return isTop;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                isTop = false;
                if (null != swipeRefreshLayout) {
                    swipeRefreshLayout.setEnabled(false);
                }
                break;
            case MotionEvent.ACTION_UP:
                isTop = false;
                if (null != swipeRefreshLayout) {
                    swipeRefreshLayout.setEnabled(false);
                }
                break;
        }
        return super.onTouchEvent(event);
    }
}
